﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessLayer.Model.Repositories.Abstract;
using BusinessLayer.Model.Entities;
using System.Data.Linq;

namespace DataAccess.Repositories
{
    public class NewsRepository : INewsRepository
    {

        private readonly IntecDataContext _db = new IntecDataContext();
        private readonly Table<News> _newsTable;

        public NewsRepository()
        {
            //_db.CreateDatabase();
            _newsTable = _db.GetTable<News>();
        }

        #region INewsRepository Members

        public News FetchByTitle(string title)
        {
            return (from n in _newsTable
                    where n.Title == title
                    select n).First();
        }

        public News FetchByID(Guid id)
        {
            return (from n in _newsTable
                    where n.NewsID == id
                    select n).First();
        }

        public IEnumerable<News> FetchAll()
        {
            return _newsTable.AsEnumerable<News>();
        }

        public IEnumerable<News> FetchLastNews(int amount)
        {
            IEnumerable<News> allNews = FetchAll();

            if (allNews != null && amount > 0)
                return allNews.Count() <= amount ? allNews.OrderByDescending(n => n.Date) :
                    allNews.OrderByDescending(n => n.Date).Take(amount);
            else
                return null;
        }

        public void InsertOnSubmit(News news)
        {
            _newsTable.InsertOnSubmit(news);
        }

        public void InsertOnSubmit(string title, string description, string content)
        {
            InsertOnSubmit(new News(title, description, content));
        }

        public void UpdateOnSubmit(News news)
        {
            //linq to sql resuelve solo
            return;
        }

        public void DeleteOnSubmit(News news)
        {
            _newsTable.DeleteOnSubmit(news);
        }

        public void SubmitChanges()
        {
            _db.SubmitChanges();
        }

        #endregion
    }
}
